#!/usr/bin/env python

import os
import pickle
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from encode_truth import encode_truth


siteid = 'KPNS'


def main(ndays):
    # Load the site data
    hpcd = pickle.load(open('%s_hpc_archive.pickle' % siteid.upper(), 'r'))
    verifyd = encode_truth(siteid.upper())

    # Get a list of dates
    datelist = hpcd.keys()
    datelist.sort()
   
    # We only want to look at the last ndays
    datelist = datelist[-(ndays+1):]
 
    # Make a list of median and truth
    medianlist = [np.median(hpcd[d]) for d in datelist]
    truthlist = [verifyd[d].precip for d in datelist[:-1]]
    truthlist.append(np.nan) # We don't know today's value
    errorlist = [x-y for x,y in zip(medianlist,truthlist)] 


    # Make a plot
    plt.figure(figsize=(12,12))
    plt.subplot(2,1,1)
    truplot = plt.plot(datelist,truthlist,'k-',linewdith=4,gid='truth')
    plt.hold(True)
    medplot = plt.plot(datelist,medianlist,'b-',linewdith=3,gid='hpc')

    #point out tomorrow's forecast
    tom_hpc = medianlist[-1]
    pylab.annotate('%1.2f'%(tom_hpc), xy=(matplotlib.dates.date2num(datelist[-1]),tom_hpc),xycoords='data', \
        textcoords='offset points', xytext=(-10,25),size='medium',va="center",ha="left",bbox=dict(boxstyle="round4", fc="w", edgecolor='b'),\
        arrowprops=dict(arrowstyle="->",edgecolor='b'))

    ymin,ymax = plt.ylim()
    plt.ylim(ymin = 0.0)
    leg = plt.legend([medplot,truplot],['HPC Median','Actual'],loc=2)
    ltexts = leg.get_texts()
    plt.setp(ltexts,fontsize='small')
    plt.title('Past %d-day forecast precip comparison at %s (12Z HPC)' % (ndays,siteid.upper()))
    ax = plt.gca()
    ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter('%b %d'))
    #ax.set_yticks(range(int(ymin)-1,int(ymax)+1))
    plt.grid()
    plt.ylabel('Precipitation (in.)')

    # Now the error bars
    #plt.subplot(2,1,2)
    plt.show()



if __name__ == '__main__':
    main(10)
